/**
 * @file 浏览器URL参数处理
 * @date 2017-09-16
 * @author sunshaocheng
 */

'use strict';

let url = {
    getPageName() {
        let u = location.pathname;
        let a = u.split(/\//);
        let m = a.pop().match(/(?:^|\/)($|[^\.]+)/);

        return m[1] ? m[1] : 'index';
    },

    getQuery(name) {
        // let u = location.search.slice(1);
        // let re = new RegExp(name + '=([^&\\s+]+)');
        // let m = u.match(re);
        // let v = m ? m[1] : '';

        // return (v === '' || isNaN(v)) ? v : v - 0;
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
        let r = window.location.search.substr(1).match(reg); 
        if (r != null) return unescape(r[2]); return null; 
    },

    getHash(name) {
        let u = location.hash.slice(1);
        let re = new RegExp(name + '=([^&\\s+]+)');
        let m = u.match(re);
        let v = m ? m[1] : '';

        return (v === '' || isNaN(v)) ? v : v - 0;
    },

    parseUrl(url) {
        let a = document.createElement('a');

        a.href = (url || 'x.html');

        return {
            host: a.host,
            protocol: a.protocol
        };
    },

    serialize(obj) {
        let s = [];

        for (let k in obj) {
            s.push(k + '=' + encodeURIComponent(obj[k]));
        }

        return s.join('&');
    }
}

export default url;
